<template>
  <div>
    <el-dialog 
    :title="addInfo.isAdd ? '添加商品' : '编辑商品'" 
    :visible.sync="addInfo.isShow" 
    :before-close="cancel" 
    center
    @opened="creatEditor"
    >
      <el-form :model="goodsForm" :rules="rules" ref="goodsForm">
        <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
          <el-select  v-model="goodsForm.first_cateid" placeholder="请选择" @change="changeCate(false)">
            <el-option 
            v-for="item in catelist" 
            :key="item.id" 
            :label="item.catename" 
            :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
          <el-select  v-model="goodsForm.second_cateid" placeholder="请选择">
            <el-option 
            v-for="item in secondCatearr" 
            :key="item.id" 
            :label="item.catename" 
            :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
          <el-input autocomplete="off" v-model="goodsForm.goodsname" ></el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input autocomplete="off" v-model="goodsForm.price" ></el-input>
        </el-form-item>
        <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
          <el-input autocomplete="off" v-model="goodsForm.market_price" ></el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="onPreview"
            :on-change="onChange"
            :on-exceed="onExceed"
            :file-list="fileList"
            :limit="1"
            >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
          <el-select  v-model="goodsForm.specsid" placeholder="请选择" @change="changeSpecs(false)">
            <el-option 
            v-for="item in specsArr" 
            :key="item.id" 
            :label="item.specsname" 
            :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
          <el-select  v-model="goodsForm.specsattr" placeholder="请选择" multiple>
            <el-option 
            v-for="item in attrArr" 
            :key="item" 
            :label="item" 
            :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="goodsForm.isnew" :label="1">是</el-radio>
          <el-radio v-model="goodsForm.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="goodsForm.ishot" :label="1">是</el-radio>
          <el-radio v-model="goodsForm.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch 
          v-model="goodsForm.status" 
          active-color="#13ce66" 
          inactive-color="#ff4949" 
          :active-value="1"
          :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="confirn" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import { goodsadd, goodsinfo, goodsedit,getspecslist } from '../../request/api';
import E from 'wangeditor'
export default {
  props: ['addInfo'],
  data() {
    return {
      formLabelWidth: '120px',
      goodsForm: {
        first_cateid:'',//一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: '', //商品价格
        market_price: '', //市场价格
        img: '', //商品图片（文件）
        description: '', //商品描述
        specsid: '', //商品规格编号
        specsattr: '', //商品规格属性
        isnew: '', //是否新品
        ishot: '', //是否热卖推荐
        status: 1, //状态1正常2禁用
      },
      rules: {
        goodsname: [
          { required: true, message: '请输入商品分类名称', trigger: 'blur' },
          { min: 2, max: 11, message: '长度在 2 到 11 个字符', trigger: 'blur' }
        ],
        first_cateid: [
          { required: true, message: '请输入一级分类', trigger: 'change' }  
        ],
        second_cateid: [
          { required: true, message: '请输入二级分类', trigger: 'blur' }  
        ],
        specsid: [
          { required: true, message: '请输入商品规格', trigger: 'change' }  
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }  
        ],
        market_price: [
          { required: true, message: '请输入市场价格', trigger: 'blur' }  
        ],
        specsattr: [
          { required: true, message: '请输入规格属性', trigger: 'blur' }  
        ],
      },
      dialogImageUrl:'',//图片地址
      dialogVisible:false,//控制图片预览的显示隐藏
      fileList:[],//文件列表
      secondCatearr:[],//二级分类数组
      specsArr:[],//规格列表
      attrArr:[],//规格属性
      editor:null //编辑器初始值
    }
  },
  mounted() {
    this.getcateAction();
    this.getSpecs();
  },
  computed:{
    ...mapGetters({
      catelist:'cate/getCate'
    })
  },
  methods: {
    //封装一个创建编辑器的方法
    creatEditor(){
      // console.log(2222222);
      //初始化编辑器
      this.editor = new E('#editor');
      //创建
      this.editor.create();
      //赋值初始值
      this.editor.txt.html(this.goodsForm.description)
    },
    ...mapActions({
      getcateAction:'cate/getcateAction',
      getCount:'goods/getCountAction',
      getGoodsAction:'goods/getGoodsAction',
    }),
    //封装获取商品规格的接口
    getSpecs(){
      getspecslist().then(res=>{
        console.log(res);
        this.specsArr = res.list;
      })
    },
    //封装一个事件，用于切换一级分类获取二级分类
    changeCate(n){
      //查找索引findIndex，怎么查找索引，我们可以根据双向数据绑定的值去数组中查找
      let index = this.catelist.findIndex((item)=>this.goodsForm.first_cateid == item.id);
      this.secondCatearr = this.catelist[index].children;
      // console.log(secondCatearr,'xxxxx');
      //清空二级分类双向数据绑定值
      if (!n) {
        this.goodsForm.second_cateid = ''
      }
    },
    changeSpecs(n){
      let index = this.specsArr.findIndex((item)=>this.goodsForm.specsid == item.id);
      this.attrArr = this.specsArr[index].attrs;
      // console.log(this.attrArr,'dfgdfgfdg');
      if (!n) {
        this.goodsForm.specsattr = []
      }
    },
    //图片预览
    onPreview(file){
      // console.log(file,'文件预览');
      //显示弹框
      this.dialogVisible = true;
      this.dialogImageUrl = file.url
    },
    //图片改变时发生的变化
    onChange(file, fileList){
      // console.log(file,'文件');
      // console.log(fileList,'文件列表');
      this.goodsForm.img = file.raw
    },
    //超出文件上传的回调函数
    onExceed(files, fileList){
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    reset() {
      this.goodsForm = {
        first_cateid:'',//一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: '', //商品价格
        market_price: '', //市场价格
        img: '', //商品图片（文件）
        description: '', //商品描述
        specsid: '', //商品规格编号
        specsattr: '', //商品规格属性
        isnew: '', //是否新品
        ishot: '', //是否热卖推荐
        status: 1, //状态1正常2禁用
      };
      this.$refs.goodsForm.resetFields();//重置表单验证
      //清空上传文件
      this.fileList=[]
    },
    //取消事件
    cancel() {
      this.$emit('cancel', false);
      //清空
      this.reset();
    },
    //数据回显
    lookup(id) {
      goodsinfo({ id }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.goodsForm = res.list;
          this.goodsForm.id = id;
          //对图片进行数据回显
          this.fileList = this.goodsForm.img ? [{url:this.goodsForm.img}] : []
          //我们要对二级分类 以及 规格属性进行结构转化
          //规格属性
          this.goodsForm.specsattr = this.goodsForm.specsattr.split(',');
          //转化二级分类，如果我们是回显 我们就不去change里面清空二级
          this.changeCate(true);
          this.changeSpecs(true)
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    //确定事件
    confirn() {
      // console.log(this.goodsForm);
      this.$refs.goodsForm.validate((valid) => {
        if (valid) {
          this.goodsForm.specsattr = this.goodsForm.specsattr.join(',')
          if (this.addInfo.isAdd) {
            //添加逻辑
            goodsadd(this.goodsForm).then((res) => {
              // console.log(res);
              if (res.code == 200) {
                this.cancel();
                this.getCount();
                this.getGoodsAction()
                //添加成功
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg)
              }
            })
          }else{
            //编辑逻辑
            goodsedit(this.goodsForm).then((res)=>{
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getCount();
                this.getGoodsAction()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }else{
          this.$message.error('验证失败')
          return false
        }
      })
    },
    //图片预览
    onPreview(file){
      console.log(file,'文件预览');
      //显示弹框
      this.dialogVisible = true;
      this.dialogImageUrl = file.url
    },
    //图片移除
    
    //图片改变时发生的变化
    onChange(file, fileList){
      console.log(file,'文件');
      console.log(fileList,'文件列表');
      this.goodsForm.img = file.raw
    },
    //超出文件上传的回调函数
    onExceed(files, fileList){
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  },
};
</script>

<style scoped>

</style>
